import React, { memo, useEffect, useState } from 'react'
import styles from './index.module.css'

import { Input, Table, Form, Select, Button, Space, Drawer, } from 'antd'
import { CaretDownOutlined, PlusOutlined } from '@ant-design/icons'

import { queryAllDevicesApi, queryAllSelectsApi, addDeviceApi, editDeviceApi, deleteDeviceApi } from '../../api/device'
import { useNotification } from '../../utils/notificationContext'
import useTableDataEffect from '../../hook/table-hook'
import useInnerDrawer from '../../hook/inner-drawer'
import dayjs from 'dayjs'

const triangleIcon = <CaretDownOutlined style={{ pointerEvents: "none" }} />

const layout = {
  labelCol: {
    span: 6,
  },
  labelAlign: 'right',
  wrapperCol: {
    span: 24,
  },
};

const tailLayout = {
  wrapperCol: {
    offset: 24, //	栅格左侧的间隔格数，间隔内不可以有栅格
    span: 16, //栅格占位格数，为 0 时相当于 display: none
  },
};

const DeviceManage = memo(() => {
  // const [page, setPage] = useState(1)
  // const [pageSize, setPageSize] = useState(10)
  const [search, setSearch] = useState({})

  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [drawerTitle, setDrawerTitle] = useState('');
  const [operation, setOperation] = useState('');

  const { openNotification } = useNotification()

  const { tableData, total, queryAllInfo } = useTableDataEffect(queryAllDevicesApi, search)
  // const { tableData, total, queryAllInfo } = useTableDataEffect(queryAllDevicesApi, {pageNum: page, pageSize, ...search}, CancelToken)

  const { containerStyle } = useInnerDrawer()

  const [allSelectOptions, setAllSelectOptions] = useState({})
  const [isSave, setIsSave] = useState(false)
  useEffect(() => {
    const queryAllSelects = async () => {
      try {
        const queryAllSelectsRes = await queryAllSelectsApi()
        if (queryAllSelectsRes.code === 200) {
          setAllSelectOptions(queryAllSelectsRes.data)
        } 
      } catch (error) {
        console.log(error);
      }
    }
    queryAllSelects()
  },[isSave])

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: '8%',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '设备编号',
      dataIndex: 'deviceNo',
      key: 'deviceNo',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      key: 'type',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '设备型号',
      dataIndex: 'model',
      key: 'model',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
      render: (_, record) => (
        <div className={styles.user_status_wrap}>
          <span className={`${styles.user_status_dot} ${record.status === 1 ? styles.user_status_dot_active : ''}`}></span>
          <span>{record.status === 1 ? '使用中' : '待启用'}</span>
        </div>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
      width: '8%',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '管理员',
      dataIndex: 'manager',
      key: 'manager',
      width: '8%',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: 'center',
      width: '8%',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
      render: (_, record) => (
        <>
          <span>{record.updateTime ? dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')  : dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }</span>
        </>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: '15%',
      // ellipsis: true,
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
      render: (_, record) => (
        <>
          <div className={styles.wrap_note_wrap}>
            <span className={styles.wrap_note}>{record.remark}</span>
          </div>
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      onCell(record,index){
        return {
          className: styles['table-thead-column']
        }
      },
      onHeaderCell(record,index){
        return {
          className: styles['table_column']
        }
      },
      render: (_, record) => (
        <>
          <button className={styles.table_operation_add} onClick={() => rowOperation(record, 'edit')}>编辑</button>
          <button className={styles.table_operation_add} onClick={() => rowOperation(record, 'delete')}>删除</button>
        </>
      ),
    },
  ];

  const rowOperation = (record, operation) => {
    switch (operation) {
      case 'add':
        console.log('新增设备');
        setOpen(true)
        setDrawerTitle('新增设备')
        setOperation(operation)
        form.resetFields();
        form.setFieldsValue({status: 1});
        break;
      case 'edit':
        setOpen(true)
        setDrawerTitle('编辑设备')
        setOperation(operation)
        form.setFieldsValue(record);
        break;
      case 'delete':
        console.log('删除');
        setOperation(operation)
        deleteDevice(record)
        break;
      default:
        break;
    }
  }

  const onSearch = (values) => {
    console.log('search', values)  // 点击搜索后，打印出搜索的关键词
    // setPage(1)
    setSearch(values)
  }
  const onReset = () => {
    JSON.stringify(search) !== '{}' && setSearch({})
    searchForm.resetFields();
  };

  const onFinish = (values,operation) => {
    switch (operation) {
      case 'add':
        console.log('新增保存', values, operation);
        addDevice(values)
        break;
      case 'edit':
        console.log('修改保存', values, operation);
        editDevice(values)
        break;
      default:
        break;
    }
  }

  // ------------网络请求------------------------------
  const addDevice = (values) => {
    addDeviceApi(values).then(addRes => {
      console.log(addRes);
      if (addRes.code === 200) {
        openNotification('新增成功~', 'success');
        setOpen(false)
        setIsSave(!isSave)
        queryAllInfo(false)
      } else {
        openNotification(addRes.msg, 'fail');
      }
    }).catch(addErr => {
      console.log(addErr);
      openNotification('新增失败', 'fail');
    })  
  }

  const editDevice = (values) => {
    editDeviceApi(values).then(updateRes => {
      console.log(updateRes);
      if (updateRes.code === 200) {
        openNotification('修改成功~', 'success');
        setOpen(false)
        setIsSave(!isSave)
        queryAllInfo(false)
      }else{
        openNotification(updateRes.msg, 'fail');
      }
    }).catch(updateErr => {
      console.log(updateErr);
      openNotification('修改异常', 'fail');
    })
  }

  const deleteDevice = (data) => {
    deleteDeviceApi(data).then(deleteRes => {
      console.log(deleteRes);
      if (deleteRes.code === 200) {
        openNotification('删除成功', 'success');
        queryAllInfo(false)
      }
    }).catch(deleteErr => {
      console.log(deleteErr);
      openNotification('删除失败', 'fail');
    })
  }

  return (
    <div className={`${styles.container}`} style={containerStyle}>
      <div className={`${styles.container_common} ${styles.container_top}`}>
        <Form
          form={searchForm}
          name="search"
          onFinish={(values) => onSearch(values)}
          autoComplete="off"
          className={styles.form}
        >
          <div className={styles.form_wrap}>
            <div className={styles.form_wrap_item}>
              <Form.Item
                labelCol={{
                  span: 5,
                }}
                labelAlign='left'
                wrapperCol={{
                  span: 19,
                }}
                name="type"
                label="设备类型:"
              >
                <Select
                  placeholder="请选择"
                  optionFilterProp="label"
                  suffixIcon={triangleIcon}
                  options={allSelectOptions?.typeList?.map(item => ({ value: item, label: item }))}
                />
              </Form.Item>
            </div>
            <div className={styles.form_wrap_item}>
              <Form.Item
                labelCol={{
                  span: 5,
                }}
                labelAlign='right'
                wrapperCol={{
                  span: 19,
                }}
                name="status"
                label="状态:"
              >
                <Select
                  placeholder="请选择"
                  optionFilterProp="label"
                  suffixIcon={triangleIcon}
                  options={[
                    {
                      value: 1,
                      label: '使用中',
                    },
                    {
                      value: 0,
                      label: '待启用',
                    },
                  ]}
                />
              </Form.Item>
            </div>
            <div className={styles.form_wrap_item}>
              <Form.Item
                labelCol={{
                  span: 5,
                }}
                labelAlign='right'
                wrapperCol={{
                  span: 19,
                }}
                name="manager"
                label="管理员:"
              >
                <Select
                  placeholder="请选择"
                  optionFilterProp="label"
                  suffixIcon={triangleIcon}
                  options={allSelectOptions?.managerList?.map(item => ({ value: item, label: item }))}
                />
              </Form.Item>
            </div>
            <div className={styles.form_wrap_item}>
              <Form.Item
                labelCol={{
                  span: 5,
                }}
                labelAlign='right'
                wrapperCol={{
                  span: 19,
                }}
                name="brand"
                label="品牌:"
              >
                <Select
                  placeholder="请选择"
                  optionFilterProp="label"
                  suffixIcon={triangleIcon}
                  options={allSelectOptions?.brandList?.map(item => ({ value: item, label: item }))}
                />
              </Form.Item>
            </div> 
            <div className={styles.form_wrap_item}>
              <Form.Item
                label="关键字搜索:"
                name="keywords"
              >
                {/* <Input placeholder='请输入设备名称' autoComplete='off' suffix={<SearchOutlined style={{color: '#ccc'}} />} /> */}
                <Input placeholder='请输入设备名称' autoComplete='off' />
              </Form.Item>
            </div>
            <div className={`${styles.form_wrap_item} ${styles.form_wrap_item_submit}`}>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" style={{background: '#6977D0'}}>查询</Button>
                  <Button htmlType="button" onClick={onReset}>重置</Button>
                </Space>
              </Form.Item>
            </div>
          </div>
        </Form>
      </div>
      <div className={`${styles.container_common} ${styles.container_bottom}`}>
         <div className={styles.title_wrap}>
          <h2>设备台账</h2>
          <button onClick={() => rowOperation(null, 'add')}>
            <PlusOutlined style={{color: '#fff'}} />
            <span className={styles.add_device}>新增设备</span>
          </button>
        </div>
       <div className={`${styles.table_wrap}`}>
          <Table
            size='small'
            className={styles.table}
            columns={columns}
            rowHoverable={false}
            // pagination={false}
            pagination={{
              // current: page,
              total,
              // pageSize,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共${total}条`,
              // onChange: (page, pageSize) => {setPage(page);setPageSize(pageSize)},
              // onShowSizeChange: (current, size) => {setPage(current);setPageSize(size)}
            }}
            scroll={tableData.length > 6.4 ?{
              y: 80 * 6.4,
              x: 0,
            }: null}
            dataSource={tableData}
            rowKey={record => record.key}
          />
        </div>
      </div>

      <Drawer
        title={drawerTitle}
        width={520}
        closable
        destroyOnClose
        placement="right"
        open={open}
        onClose={() => setOpen(false)}
        getContainer={false}
      >
      <Form
        {...layout}
        form={form}
        name="device-form"
        onFinish={(values) => onFinish(values, operation)}
        autoComplete="off"
        className={styles.drawer_form}
      >
        {
          operation === 'edit' && <Form.Item
            label=""
            name="id"
            style={{display: 'none'}}
          >
            <Input hidden />
          </Form.Item>
        }
        <Form.Item
          label="设备编号:"
          name="deviceNo"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入设备编号',
          //   },
          // ]}
        >
          <Input placeholder='请输入设备编号' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          label="设备类型:"
          name="type"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入设备类型',
          //   },
          // ]}
        >
          <Input placeholder='请输入设备类型' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          label="设备名称:"
          name="name"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入设备名称',
          //   },
          // ]}
        >
          <Input placeholder='请输入设备名称' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          label="设备型号:"
          name="model"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入设备型号',
          //   },
          // ]}
        >
          <Input placeholder='请输入设备型号' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          label="品牌:"
          name="brand"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入品牌',
          //   },
          // ]}
        >
          <Input placeholder='请输入品牌' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          label="管理员:"
          name="manager"
          className={styles.form_item}
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入管理员',
          //   },
          // ]}
        >
          <Input placeholder='请输入管理员' autoComplete='off'/>
        </Form.Item>
        <Form.Item
          name="status"
          label="状态:"
          className={styles.form_item}
        >
          <Select
            placeholder="请选择"
            optionFilterProp="label"
            suffixIcon={triangleIcon}
            options={[
              {
                value: 1,
                label: '使用中',
              },
              {
                value: 0,
                label: '待启用',
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="描述:"
          className={styles.form_item}
          name="remark"
          // rules={[
          //   {
          //     // required: true,
          //     message: '请输入',
          //   },
          // ]}
        >
          <Input.TextArea placeholder='请输入' autoSize maxLength={280} autoComplete='off'/>
        </Form.Item>
        <Form.Item {...tailLayout} className={styles.operation_wrap}>
          <Space>
            <Button htmlType="button" onClick={() => setOpen(false)}>取消</Button>
            <Button type="primary" htmlType="submit" style={{background: '#6977D0'}}>确定</Button>
          </Space>
        </Form.Item>
      </Form>
      </Drawer>
    </div>
  )
})

export default DeviceManage